package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.KeyboardUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.DecimalInputUtils;
import com.cj.mobile.iabp.app.utils.EventBusTags;
import com.cj.mobile.iabp.di.component.DaggerAddArchiveInfoComponent;
import com.cj.mobile.iabp.mvp.contract.AddArchiveInfoContract;
import com.cj.mobile.iabp.mvp.model.entity.ArchiveInfo;
import com.cj.mobile.iabp.mvp.model.entity.DictInfo;
import com.cj.mobile.iabp.mvp.model.entity.MainEvent;
import com.cj.mobile.iabp.mvp.presenter.AddArchiveInfoPresenter;
import com.cj.mobile.iabp.mvp.ui.adapter.PrimaryDiagnosisAdapter;
import com.cj.mobile.iabp.mvp.ui.adapter.SecondaryDiagnosisAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import javax.inject.Inject;
import javax.inject.Named;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2025/10/01 11:22
 * 归档信息
 *
 * @author Love_xie
 * module name is AddArchiveInfoActivity
 */
public class AddArchiveInfoActivity extends BaseActivity<AddArchiveInfoPresenter> implements AddArchiveInfoContract.View {

    /*----------------------------------------------------------------控件信息----------------------------------------------------------------*/
    @BindView(R.id.txvi_addarchiveinfo_code)
    TextView txviCode;                                                                              // 登记号
    @BindView(R.id.txvi_addarchiveinfo_name)
    TextView txviName;                                                                              // 患者姓名

    @BindView(R.id.group_addarchiveinfo_archive)
    RadioGroup rgArchive;                                                                           // 归档
    @BindView(R.id.group_addarchiveinfo_state)
    RadioGroup rgState;                                                                             // 状态
    @BindView(R.id.edit_addarchiveinfo_ga)
    EditText editGa;                                                                                // 肌钙蛋白
    @BindView(R.id.edit_addarchiveinfo_zsszmqnj)
    EditText editZsszmqnj;                                                                          // 出院前左室舒张末期内径
    @BindView(R.id.edit_addarchiveinfo_zssxfs)
    EditText editZssxfs;                                                                            // 出院前左室射血分数

    @BindView(R.id.revi_addarchiveinfo_primarydiagnosis)
    RecyclerView reviPrimaryDiagnosis;                                                              // 主要诊断
    @BindView(R.id.txvi_addarchiveinfo_primarydiagnosis)
    TextView txviPrimaryDiagnosis;
    @BindView(R.id.revi_addarchiveinfo_secondarydiagnosis)
    RecyclerView reviSecondaryDiagnosis;                                                            // 次要诊断
    @BindView(R.id.txvi_addarchiveinfo_secondarydiagnosis)
    TextView txviSecondaryDiagnosis;
    @BindView(R.id.edit_addarchiveinfo_other)
    EditText editOther;                                                                             // 其它诊断

    @BindView(R.id.edit_addarchiveinfo_icu)
    EditText editIcu;                                                                               // ICU
    @BindView(R.id.edit_addarchiveinfo_ventilation)
    EditText editVentilation;                                                                       // 机械通气时间
    @BindView(R.id.edit_addarchiveinfo_zytime)
    EditText editZyTime;                                                                            // 住院天数

    /*----------------------------------------------------------------业务信息----------------------------------------------------------------*/

    // 对话框
    private MaterialDialog mDialog;

    @Named("PrimaryLayout")
    @Inject
    RecyclerView.LayoutManager mPrimaryLayoutManager;
    @Named("PrimaryAdapter")
    @Inject
    PrimaryDiagnosisAdapter mPrimaryAdapter;

    @Named("SecondaryLayout")
    @Inject
    RecyclerView.LayoutManager mSecondaryLayoutManager;
    @Named("SecondaryAdapter")
    @Inject
    SecondaryDiagnosisAdapter mSecondaryAdapter;

    @Override
    protected void onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        if (mDialog != null) {
            this.mDialog.dismiss();
        }
        super.onDestroy();

        this.mDialog = null;
    }

    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerAddArchiveInfoComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_add_archive_info;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        setTitle("出院归档信息");

        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.common_execute).progress(true, 0).build();

        initRecyclerView();

        // 创建输入框数组
        EditText[] decimalInputs = {editGa, editZsszmqnj, editZssxfs, editIcu, editVentilation, editZyTime};
        // 批量设置，限制小数点后2位
        DecimalInputUtils.setupDecimalInputs(decimalInputs, 2);

        if (mPresenter != null) {
            mPresenter.initData(getIntent().getExtras());
        }
    }

    private void initRecyclerView() {
        ArmsUtils.configRecyclerView(reviPrimaryDiagnosis, mPrimaryLayoutManager);
        reviPrimaryDiagnosis.setAdapter(mPrimaryAdapter);
        mPrimaryAdapter.setOnItemClickListener((view, viewType, data, position) -> {
            DictInfo info = (DictInfo) data;
            primaryData(info);
        });


        ArmsUtils.configRecyclerView(reviSecondaryDiagnosis, mSecondaryLayoutManager);
        reviSecondaryDiagnosis.setAdapter(mSecondaryAdapter);
        mSecondaryAdapter.setOnItemClickListener((view, viewType, data, position) -> {
            DictInfo info = (DictInfo) data;
            info.setCheckBox(!info.isCheckBox());
        });
    }

    @Subscriber(tag = EventBusTags.HOME_TAG, mode = ThreadMode.POST)
    private void eventBusEvent(MainEvent mainEvent) {
        if (mainEvent.getCode() == EventBusTags.REFRESH_HOME_INFO_TAG) {
            // 主要诊断
            primaryData(mainEvent.getInfo());
        }
    }

    /**
     * 处理主要诊断数据，只能选一项
     */
    private void primaryData(DictInfo info) {
        for (DictInfo item : mPrimaryAdapter.getInfos()) {
            item.setCheckBox(false);
        }

        info.setCheckBox(true);

        mPrimaryAdapter.notifyDataSetChanged();
    }

    @OnClick({
            R.id.btn_addarchiveinfo_save,                                                           // 保存
            R.id.btn_addarchiveinfo_submit,                                                         // 提交
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_addarchiveinfo_save:
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("0");
                }
                break;
            case R.id.btn_addarchiveinfo_submit:
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("1");
                }
                break;
        }
    }

    private void onSubmit(String pre) {
        if (mPresenter != null) {
            mPresenter.btnSubmit(pre, "",
                    getArchive(), getState(),
                    editGa.getText().toString(),
                    editZsszmqnj.getText().toString(),
                    editZssxfs.getText().toString(),
                    editOther.getText().toString(),
                    editIcu.getText().toString(),
                    editVentilation.getText().toString(),
                    editZyTime.getText().toString()
            );
        }
    }

    private String getArchive() {
        if (rgArchive.getCheckedRadioButtonId() != -1) {
            if (rgArchive.getCheckedRadioButtonId() == R.id.radio_addarchiveinfo_archive_yes) {
                return "是";
            } else {
                return "否";
            }
        }

        return "";
    }


    private String getState() {
        if (rgState.getCheckedRadioButtonId() != -1) {
            if (rgState.getCheckedRadioButtonId() == R.id.radio_addarchiveinfo_state_survive) {
                return "存活";
            } else {
                return "死亡";
            }
        }

        return "";
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {
        txviPrimaryDiagnosis.setVisibility(View.GONE);
        txviSecondaryDiagnosis.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    /**
     * 诊断没有数据
     */
    @Override
    public void notDiagnosis() {
        txviPrimaryDiagnosis.setVisibility(View.VISIBLE);
        txviSecondaryDiagnosis.setVisibility(View.VISIBLE);
    }

    @Override
    public void showArchiveInfo(String code, String name, ArchiveInfo info) {
        txviCode.setText(CommonUtils.isEmptyReturnStr(code, "暂无"));
        txviName.setText(CommonUtils.isEmptyReturnStr(name));

        if (info != null) {

            // 归档状态
            if (!TextUtils.isEmpty(info.getStatus())) {
                if (info.getStatus().equals("是")) {
                    ((RadioButton) findViewById(R.id.radio_addarchiveinfo_archive_yes)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addarchiveinfo_archive_not)).setChecked(true);
                }
            }

            // 存活状态
            if (!TextUtils.isEmpty(info.getAlive())) {
                if (info.getAlive().equals("存活")) {
                    ((RadioButton) findViewById(R.id.radio_addarchiveinfo_state_survive)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addarchiveinfo_state_death)).setChecked(true);
                }
            }

            editGa.setText(CommonUtils.isEmptyReturnStr(info.getGa()));
            editZsszmqnj.setText(CommonUtils.isEmptyReturnStr(info.getLeftSize()));
            editZssxfs.setText(CommonUtils.isEmptyReturnStr(info.getLeftScore()));

            editOther.setText(CommonUtils.isEmptyReturnStr(info.getDiagContent()));

            editIcu.setText(CommonUtils.isEmptyReturnStr(info.getTimeIcu()));
            editVentilation.setText(CommonUtils.isEmptyReturnStr(info.getTimeMc()));
            editZyTime.setText(CommonUtils.isEmptyReturnStr(info.getRunTime()));

        }
    }

    @Override
    public void hideLoadingSubmit() {
        if (mDialog != null)
            mDialog.cancel();
    }

    @Override
    public void showLoadingSubmit() {
        if (mDialog != null)
            mDialog.show();
    }
}